import * as uuid from "uuid/v4";
import * as WebSocket from "ws";

import { EventEmitter } from "events";
import log from "../../lib/log";

export class Socket {
    public clients: { [key: string]: any };
    public ws: WebSocket.Server;


    constructor(socketEvent: EventEmitter) {
        this.clients = {};
        this.ws = new WebSocket.Server({ port: 1028 });
        console.log("websocket port:", 1028);

        this.ws.on("connection", (client) => {
            const socketId = uuid();
            this.clients[socketId] = client;
            client.on("message", (data: string) => {
                const message = JSON.parse(data);
                message.token = socketId;
                socketEvent.emit(message.type, message, (result) => {
                    this.send({
                        result,
                        callbackId: message.callbackId,
                    }, message.socketId);
                });
                // log.app.info(message);
            });
        
            client.on("close", () => {
                delete this.clients[socketId];
                socketEvent.emit("logout", { token: socketId });
                log.app.info("logout", socketId);
            });
        });
    }

    public send(message: { [key: string]: any }, socketId?: string) {
        return new Promise((resolve) => {
            if (!socketId) {
                for (const id in this.clients) {
                    this.clients[id].send(JSON.stringify(message), resolve);
                }
            } else if (this.clients[socketId]) {
                this.clients[socketId].send(JSON.stringify(message), resolve);
            } else {
                resolve();
            }
            // log.app.info(message, socketId);
        });
    }

    public close(socketId: string) {
        if (this.clients[socketId]) {
            this.clients[socketId].close();
        }
    }
}